package com.qf.gh.dao.impl;

import com.qf.gh.dao.UserDao;
import com.qf.gh.domain.User;
import com.qf.gh.utils.DateSourceUtils;
import com.qf.gh.utils.MD5Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public long selectCountByUsername(String username) {
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        String sql = "select count(0) from tb_user where username = ?";
        try {
            Long count = (Long) qr.query(sql, new ScalarHandler(), username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("检查用户名是否存在失败");
        }
        return 0;
    }

    @Override
    public int insert(User user) {
        QueryRunner qr = new QueryRunner(DateSourceUtils.getDataSource());
        String sql = "insert into tb_user values(null ,?,md5(?),?,?,?,?,?)";
        try {
            int count = qr.update(sql, user.getUsername(),
                    user.getPassword(), user.getEmail(), user.getGender(), user.getFlag(), 1, "");
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("注册用户失败!!!");
        }
        return  0;
    }

    @Override
    public User select(String username, String password) {
       QueryRunner qr=new QueryRunner(DateSourceUtils.getDataSource());

       User user=null;
       String sql="select id ,username, password ,email, gender, flag ,role, code from tb_user where username=? and password=md5(?)";
        try {
            user=qr.query(sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public User selectById(int uid) {
        QueryRunner qr=new QueryRunner(DateSourceUtils.getDataSource());

        User user=null;
        String sql="select id ,username, password ,email, gender, flag ,role, code from tb_user where id=?";
        try {
            user=qr.query(sql,new BeanHandler<>(User.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
